package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@Api(tags = "上传")
@RequestMapping("/upload")
@RestController
public class UploadController {
    @Autowired
    private IUserService userService;
    @ApiOperation("图片上传")
    @PostMapping("/upImg")
    public AppResult upload(HttpServletRequest request,@RequestPart(value = "file") MultipartFile file) throws IOException {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

            String fileName = UploadUtil.uploadImage(file);
            User updateUser = new User();
            updateUser.setId(user.getId());
            updateUser.setAvatarUrl(fileName);
            //调用Service
           userService.updateByPrimaryKeySelective(updateUser);


            return AppResult.success(fileName,fileName);

        //return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
    }
}